package com.brett.frame.learn.util;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

public class DataBuilder {
	private Integer max = Integer.MAX_VALUE;

	public int[] getDisroderArray(int len) {
		/**
		 * random参考博客
		 * https://www.cnblogs.com/uncle-box/p/5918743.html 
		 */
		Random r = new Random(System.currentTimeMillis());
		int i = 0;
		int[] arr = new int[len];
		while (i < len) {
			arr[i] = r.nextInt(getMax());
			i++;
		}
		return arr;
	}

	public Boolean asc(int[] arr) {
		for (int i = 1; i < arr.length; i++) {
			if (arr[i - 1] > arr[i]) {
//				System.err.println("非升序");
				return false;
			}
		}
//		System.err.println("升序");
		return true;
	}

	public void printArr(String prefix, int[] arr) {
		System.out.print(prefix + ":");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(String.format(" %d, ", arr[i]));
//			System.out.print(String.format("i%s=%d, ", i, arr[i]));
		}
		System.out.println(" ");
	}

	public void printArr(String prefix, int[][] arr) {
		System.out.println(prefix + ":");
		for (int i = 0; i < arr.length; i++) {
			System.out.print( String.format("i%d:",i));
			for (int j = 0; j < arr[i].length; j++) {
				System.out.print(String.format(" %d, ", arr[i][j]));
			}
			System.out.println(" ");
		}
		System.out.println(" ");
	}

	public void printHeapArr(int[] arr) {
		int[] max = this.getDepth(arr.length);
		Map<Integer, List<String>> map = new HashMap<Integer, List<String>>();
		for (int i = 0; i < arr.length; i++) {
			int[] cur = this.getDepth(i + 1);
			if (map.containsKey(cur[0])) {
				List<String> list = map.get(cur[0]);
				list.add(StringUtils.rightPad("[" + arr[i] + "]", 5));
				map.put(cur[0], list);
			} else {
				List<String> list = Lists.newArrayList();
				list.add(StringUtils.rightPad("[" + arr[i] + "]", 5));
				map.put(cur[0], list);
			}
		}
		String pad = "     ";

		List<Integer> ll = map.keySet().stream().sorted().collect(Collectors.toList());
		ll.forEach(k -> {
			List<String> i = map.get(k);
			String str = Joiner.on(pad + pad).join(i);

			System.out.println(StringUtils.leftPad(str, 10 * (max[1] - k + 1) + str.length(), pad));
		});
	}

	public int[] getDepth(int len) {
		int layer = (int) Math.ceil(Math.log(len + 1) / Math.log(2));
		int depth = layer - 1;
//		System.out.println(String.format("len=%d, layer=%d, depth=%d", len, layer, depth));
		return new int[] { layer, depth };
	}

	public Integer getMax() {
		return max;
	}

	public DataBuilder setMax(Integer max) {
		this.max = max;
		return this;
	}

}
